package com.jing.ads.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONObject;

import com.jing.ads.application.MD5;

import android.content.Context;
import android.util.Base64;

/**
 * 客户端缓存管理中心
 * 
 * @author zhangjingbd
 * 
 */
public class CacheManager {

	private static CacheManager manager = null;

	private Context mContext;

	private ArrayList<String> keyList = new ArrayList<String>();
	
	private CacheManager(Context context) {
		mContext = context;
	}

	/**
	 * 获取缓存管理实例
	 * 
	 * @param context
	 * @return CacheManager
	 */
	public static CacheManager getInstance(Context context) {
		if (manager == null) {
			manager = new CacheManager(context);
		}
		return manager;
	}

	public boolean hasCache(String key) {
		key = MD5.MD5Encode(key);
		File file = mContext.getFileStreamPath(key);
		return file != null && file.exists();
	}

	public void pushData(String key, JSONObject data) {
		key = MD5.MD5Encode(key);
		if (!keyList.contains(key)) {
			keyList.add(key);
		}
		putToCache(key, data);
	}

	public JSONObject pullData(String key) {
		key = MD5.MD5Encode(key);
		if (!keyList.contains(key)) {
			return null;
		}
		return pullCache(key);
	}

	private void putToCache(String key, JSONObject value) {
		mContext.deleteFile(key);
		String v = value.toString();
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(key, Context.MODE_APPEND);
			byte[] data = Base64.encode(v.getBytes(), Base64.URL_SAFE);
			fos.write(data);
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private JSONObject pullCache(String key) {
		File file = mContext.getFileStreamPath(key);
		if (!file.exists()){
			return null;
		}
		FileInputStream fis = null;
		try {
			fis = mContext.openFileInput(key);
			byte[] temp = new byte[fis.available()];
			fis.read(temp);
			byte[] d = Base64.decode(temp, Base64.URL_SAFE);
			JSONObject j = new JSONObject(new String(d));
			return j;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void clear() {
		keyList.clear();
		File dir = mContext.getFilesDir();
		if (dir.exists()) {
			dir.delete();
		}
	}
}
